package service.Impl;

import com.alibaba.fastjson.JSONObject;
import entity.Gradetable;
import mapper.GradetableDao;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import service.GradetableService;
import utils.PageObject;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * (Gradetable)表服务实现类
 *
 * @author makejava
 * @since 2021-12-27 15:14:59
 */
@Service("gradetableService")
public class GradetableServiceImpl implements GradetableService {
    @Resource
    private GradetableDao gradetableDao;

    /**
     * 通过ID查询单条数据
     *
     * @param pkId 主键
     * @return 实例对象
     */
    @Override
    public Gradetable queryById(Integer pkId) {
        return this.gradetableDao.queryById(pkId);
    }

    @Override
    public List<Gradetable> queryClassnameAll() {
        List<Gradetable> gradetables = gradetableDao.queryClassnameAll();
        return gradetables;
    }

    /**
     * 查询多条数据
     *
     * @return 对象列表
     */
    @Override
    public PageObject queryAllByLimit(JSONObject limitobj) {

        PageObject pageObject = new PageObject();
        //当前第几页
        Integer page = limitobj.getInteger("page");
        //每页几条
        Integer limit = limitobj.getInteger("limit");
        //计算开始位置
        Integer startindex = (page - 1) * limit;
        List<Gradetable> curriculumLists = gradetableDao.queryAllByLimit(startindex, limit);
        //查询所有数据条数
        Integer selectcount = gradetableDao.selectcount();
        pageObject.setPageCount(page);//第几页
        pageObject.setPageSize(limit);//每页几条
        pageObject.setRowCount(selectcount);//总条数
        pageObject.setPageCurrent((selectcount - 1) / page + 1);//总页数
        pageObject.setRecords(Collections.singletonList(curriculumLists));//当前需展示数据
        return pageObject;
    }

    /**
     * 新增数据
     *
     * @param insertobj 插入数据对象
     * @return 实例对象
     */
    @Override
    public JSONObject insert(JSONObject insertobj) {

        Gradetable gradetable = new Gradetable();
        JSONObject resultobj = new JSONObject();
        //获取传入参数数据  班级编号
        gradetable.setClassid(isEmpty(insertobj.getString("classid")));
        gradetable.setClassname(isEmpty(insertobj.getString("classname")));
        gradetable.setClassnum(isEmpty(insertobj.getString("classnum")));
        gradetable.setClasszy(isEmpty(insertobj.getString("classzy")));
        gradetable.setSsxb(isEmpty(insertobj.getString("ssxb")));
        gradetable.setPkId(insertobj.getInteger("pkId"));

        if (gradetable.getPkId() != null && !gradetable.getPkId().equals(0)) {

            if ( this.update(gradetable)!=null) {
                resultobj.put("code", "0");
                resultobj.put("msg", "编辑成功");
            } else {
                resultobj.put("code", "-1");
                resultobj.put("msg", "编辑失败");
            }
        } else {


            int insert = this.gradetableDao.insert(gradetable);
            if (insert == 1) {
                resultobj.put("code", "0");
                resultobj.put("msg", "新增成功");
            } else {
                resultobj.put("code", "-1");
                resultobj.put("msg", "新增失败");
            }
        }
        return resultobj;

    }

    /**
     * 修改数据
     *
     * @param gradetable 实例对象
     * @return 实例对象
     */
    @Override
    public Gradetable update(Gradetable gradetable) {
        this.gradetableDao.update(gradetable);
        return this.queryById(gradetable.getPkId());
    }

    /**
     * 通过主键删除数据
     *
     * @param pkId 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer pkId) {
        return this.gradetableDao.deleteById(pkId) > 0;
    }

    @Override
    public JSONObject importtoExcel(MultipartFile file) throws Exception {
        List<Gradetable> list = new ArrayList<>();
        JSONObject result = new JSONObject();
        Workbook workbook = null;
        String fileName = file.getOriginalFilename();
        if (fileName.endsWith("xls")) {
            workbook = new HSSFWorkbook(file.getInputStream());
        } else if (fileName.endsWith("xlsx")) {
            workbook = new XSSFWorkbook(file.getInputStream());
        } else {
            throw new Exception("传输文件不是Excel文件!");
        }
        Sheet sheet = workbook.getSheet("Sheet1");
        int rows = sheet.getLastRowNum();
        if (rows == 0) {
            throw new Exception("行数不能为0");
        }
        int s = 0;
        for (int i = 1; i < rows + 1; i++) {
            //读取左上端单元格
            Row row = sheet.getRow(i);
            //行不为空
            if (row != null) {
                //读取cell
                Gradetable gradetable = new Gradetable();
                //班级id
                String classid = getCellValue(row.getCell(0));
                gradetable.setClassid(classid);
                //班级名称
                String classname = getCellValue(row.getCell(1));
                gradetable.setClassname(classname);
                //人数
                String classnum = getCellValue(row.getCell(2));
                gradetable.setClassnum(classnum);
                //所属系部
                String ssxb = getCellValue(row.getCell(3));
                gradetable.setSsxb(ssxb);
                //专业
                String classzy = getCellValue(row.getCell(4));
                gradetable.setClasszy(classzy);
                int insert = gradetableDao.insert(gradetable);
                s++;
                list.add(gradetable);//把实数据放入集合里
            }
        }
        if (s == rows) {
            result.put("code", "0");
            result.put("msg", "数据导入成功!");
        } else {
            result.put("code", "-1");
            result.put("msg", "数据导入失败!");
        }
        return result;
    }

    @Override
    public boolean batchImport(String fileName, MultipartFile file) {
        return false;
    }

    public String isEmpty(String str) {
        String resultstr = "";
        if (!StringUtils.isEmpty(str)) {
            resultstr = str;
        }
        return resultstr;
    }

    private String getCellValue(Cell cell) {
        String value = "";
        if (cell != null) {
            //以下是判断数据的类型
            switch (cell.getCellType()) {
                case HSSFCell.CELL_TYPE_NUMERIC://数字
                    value = cell.getNumericCellValue() + "";
                    if (HSSFDateUtil.isCellDateFormatted(cell)) {
                        Date date = cell.getDateCellValue();
                        if (date != null) {
                            value = new SimpleDateFormat("yyyy-MM-dd").format(date);
                        } else {
                            value = "";
                        }
                    } else {
                        value = new DecimalFormat("0").format(cell.getNumericCellValue());
                    }
                    break;
                case HSSFCell.CELL_TYPE_STRING: //字符串
                    value = cell.getStringCellValue();
                    break;
                case HSSFCell.CELL_TYPE_BOOLEAN: //boolean
                    value = cell.getBooleanCellValue() + "";
                    break;
                case HSSFCell.CELL_TYPE_FORMULA: //公式
                    value = cell.getCellFormula() + "";
                    break;
                case HSSFCell.CELL_TYPE_BLANK: //空值
                    value = "";
                    break;
                case HSSFCell.CELL_TYPE_ERROR: //故障
                    value = "非法字符";
                    break;
                default:
                    value = "未知类型";
                    break;
            }
        }
        return value.trim();
    }
}
